<template>
  <view class="vehicle-verify-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="实名列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @click="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <up-search v-model="searchKeyword" :clearabled="true" :showAction="false" placeholder="请输入账号、认证姓名"
            @search="handleSearch" @clear="handleClear"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="vehicle-verify-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              用户编号：<text class="number">{{ item.bizCode }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  姓名：
                </text>
                <text class="value">
                  {{ item.username }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  身份证号：
                </text>
                <text class="value">
                  {{ item.idCard }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  申请时间：
                </text>
                <text class="value">
                  {{ formatTime(item.createTime) }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  认证状态：
                </text>
                <text class="value" :class="getStatusClass(item.status)">
                  {{ getStatusText(item.status) }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  身份证图片：
                </text>
                <view class="id-card-view-btn" @click="handleViewIdCard(item)">
                  <text class="btn-text">查看图片</text>
                  <text class="iconfont icon-eye"></text>
                </view>
              </view>
            </view>
            <view class="card-footer" v-if="item.status === 1">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button type="primary" text="审核通过" class="custom-style" @click="handleApprove(item)"></up-button>
                <up-button type="warning" text="审核驳回" class="custom-style" @click="handleReject(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 身份证图片预览弹窗 -->
    <IdCardPreview :show="idCardPreviewVisible" @update:show="idCardPreviewVisible = $event"
      :userName="currentUser?.username || ''" :idNumber="currentUser?.idCard || ''"
      :frontImage="currentUser?.idCardFront || ''" :backImage="currentUser?.idCardContrary || ''" />

    <!-- 审核通过弹窗 -->
    <up-modal :show="showApproveModal" title="审核通过" :showCancelButton="true" confirmText="确认通过" 
      @confirm="handleApproveConfirm" @cancel="handleApproveCancel">
      <view class="modal-content">
        <view class="user-info">
          <text class="info-text">确定要通过 {{ currentItem?.username }} 的实名认证申请吗？</text>
        </view>
        <view class="form-item">
          <text class="label">审核备注：</text>
          <up-textarea v-model="approveForm.remark" placeholder="请输入审核备注（可选）" 
            :maxlength="200" count showWordLimit></up-textarea>
        </view>
      </view>
    </up-modal>

    <!-- 审核驳回弹窗 -->
    <up-modal :show="showRejectModal" title="审核驳回" :showCancelButton="true" confirmText="确认驳回" 
      @confirm="handleRejectConfirm" @cancel="handleRejectCancel">
      <view class="modal-content">
        <view class="user-info">
          <text class="info-text">确定要驳回 {{ currentItem?.username }} 的实名认证申请吗？</text>
        </view>
        <view class="form-item">
          <text class="label">驳回原因：<text class="required">*</text></text>
          <up-textarea v-model="rejectForm.remark" placeholder="请输入驳回原因" 
            :maxlength="200" count showWordLimit></up-textarea>
        </view>
      </view>
    </up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getRealNameVerifyList, approveRealNameVerify, rejectRealNameVerify } from '@/api';
import { formatTime } from '@/utils/tools';
import IdCardPreview from '../components/IdCardPreview.vue';

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待审核' },
  { name: '审核通过' },
  { name: '审核驳回' },
];
const currentTab = ref(0);

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 搜索关键词
const searchKeyword = ref('')

// 身份证图片预览相关
const idCardPreviewVisible = ref(false)
const currentUser = ref(null)

// 审核弹窗相关
const showApproveModal = ref(false)
const showRejectModal = ref(false)
const currentItem = ref(null)
const approveForm = ref({
  remark: ''
})
const rejectForm = ref({
  remark: ''
})

// 获取认证状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '待审核'
    case 2:
      return '审核通过'
    case 3:
      return '审核驳回'
    default:
      return '未知'
  }
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1:
      return 'status-pending'
    case 2:
      return 'status-approved'
    case 3:
      return 'status-rejected'
    default:
      return ''
  }
}

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}


// 获取实名认证列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize,
    keyword: searchKeyword.value,
    isOwn: ""
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 状态映射：-1-全部，1-待审核，2-审核通过，3-审核驳回
    let isAuthor = -1;
    if (currentTab.value === 1) {
      isAuthor = 1; // 待审核
    } else if (currentTab.value === 2) {
      isAuthor = 2; // 审核通过
    } else if (currentTab.value === 3) {
      isAuthor = 3; // 审核驳回
    }

    const result: any = await getRealNameVerifyList({ ...params, isAuthor })
    
    // 检查返回结果的success字段
    if (result.success) {
      const data = result.data
      paging.value.complete(data.records || [])
    } else {
      paging.value.complete(false)
      uni.showToast({
        title: result.msg || '获取数据失败',
        icon: 'none'
      });
    }
  } catch (error) {
    paging.value.complete(false)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  }
}


// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchKeyword.value = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 查看身份证图片
const handleViewIdCard = (item: any) => {
  currentUser.value = item;
  idCardPreviewVisible.value = true;
};

// 审核通过
const handleApprove = (item: any) => {
  currentItem.value = item
  approveForm.value.remark = ''
  showApproveModal.value = true
}

// 审核驳回
const handleReject = (item: any) => {
  currentItem.value = item
  rejectForm.value.remark = ''
  showRejectModal.value = true
}

// 审核通过确认
const handleApproveConfirm = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '处理中...'
    })

    // 调用审核通过API
    const result = await approveRealNameVerify({
      bizCode: currentItem.value.bizCode,
      dealRemark: approveForm.value.remark
    })

    // 关闭加载提示
    uni.hideLoading()

    // 检查返回结果的success字段
    if (result.success) {
      uni.showToast({
        title: '审核通过成功',
        icon: 'success'
      })
      showApproveModal.value = false
      // 刷新列表
      if (paging.value) {
        paging.value.reload()
      }
    } else {
      uni.showToast({
        title: result.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    // 关闭加载提示
    uni.hideLoading()
    uni.showToast({
      title: '网络错误',
      icon: 'error'
    })
  }
}

// 审核通过取消
const handleApproveCancel = () => {
  showApproveModal.value = false
  approveForm.value.remark = ''
}

// 审核驳回确认
const handleRejectConfirm = async () => {
  if (!rejectForm.value.remark.trim()) {
    uni.showToast({
      title: '请输入驳回原因',
      icon: 'none'
    })
    return
  }

  try {
    // 显示加载提示
    uni.showLoading({
      title: '处理中...'
    })

    // 调用审核驳回API
    const result = await rejectRealNameVerify({
      bizCode: currentItem.value.bizCode,
      dealRemark: rejectForm.value.remark
    })

    // 关闭加载提示
    uni.hideLoading()

    // 检查返回结果的success字段
    if (result.success) {
      uni.showToast({
        title: '审核驳回成功',
        icon: 'success'
      })
      showRejectModal.value = false
      // 刷新列表
      if (paging.value) {
        paging.value.reload()
      }
    } else {
      uni.showToast({
        title: result.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    // 关闭加载提示
    uni.hideLoading()
    uni.showToast({
      title: '网络错误',
      icon: 'error'
    })
  }
}

// 审核驳回取消
const handleRejectCancel = () => {
  showRejectModal.value = false
  rejectForm.value.remark = ''
}

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped>
.vehicle-verify-list {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 身份证查看按钮样式 */
.id-card-view-btn {
  display: inline-flex;
  align-items: center;
  background-color: #f0f9ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #d6e9ff;
}

.id-card-view-btn:hover {
  background-color: #e6f7ff;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.1);
}

.id-card-view-btn .btn-text {
  margin-right: 4px;
}

.id-card-view-btn .icon-eye {
  font-size: 14px;
}

/* 审核弹窗样式 */
.modal-content {
  padding: 20rpx;
}

.user-info {
  margin-bottom: 30rpx;
}

.info-text {
  font-size: 32rpx;
  color: #333;
  line-height: 1.5;
}

.form-item {
  margin-bottom: 20rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.required {
  color: #ff4757;
  margin-left: 4rpx;
}
</style>